package com.group.elmboot.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.group.elmboot.mapper.*;
import com.group.elmboot.po.Orders;
import com.group.elmboot.po.Transition;
import com.group.elmboot.po.User;
import com.group.elmboot.po.Wallet;
import com.group.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.group.elmboot.service.WalletService;


@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet> implements WalletService{

	@Autowired
	private WalletMapper walletMapper;
	@Autowired
	private TransitionMapper transitionMapper;
	@Autowired
	private BusinessMapper businessMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Value("${myapp.globalVar.withdrawalRate}")
	private String withdrawalRate;
	@Value("${myapp.globalVar.isRechargeReward}")
	private boolean isRechargeReward;
	@Value("${myapp.globalVar.rechargeThrehold}")
	private int rechargeThrehold;
	@Value("${myapp.globalVar.rechargeReward}")
	private int rechargeReward;
	@Value("${myapp.globalVar.defaultVIPOverdraftLimit}")
	private String VIPOverdraftLimit;
	@Value("${myapp.globalVar.VIPChargeMonthly}")
	private String VIPChargeMonthly;

	@Override
	public int createWallet(String userId) throws Exception{
		Wallet wallet =new Wallet(userId);
		wallet.setCreateTime(CommonUtil.getCurrentDate());
		BigDecimal overdraftLimit=new BigDecimal(VIPOverdraftLimit);
		wallet.increaseOverdraftAmount(overdraftLimit);
		if(userMapper.getVIPInfoById(userId).isVIP()) {
			wallet.openOverdraft();
		}
		return walletMapper.insert(wallet);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int payByWallet(int orderId, String redPacket) throws Exception {
		String transitionTime=CommonUtil.getCurrentDate();
		Orders order=ordersMapper.getOrdersById(orderId);
		ordersMapper.payOrders(orderId);
		businessMapper.salesPlus(order.getBusinessId());
		BigDecimal transitionAmount=new BigDecimal(order.getOrderTotal()).subtract(new BigDecimal(redPacket));
		String userIdIn=businessMapper.getBusinessById(order.getBusinessId()).getManager();
		Transition transition = new Transition(transitionTime,transitionAmount,2,order.getUserId(),userIdIn);
		transitionMapper.insert(transition);
		Wallet inWallet=walletMapper.selectById(userIdIn);
		Wallet outWallet=walletMapper.selectById(order.getUserId());
        try {
            outWallet.decreaseBalance(transitionAmount);
        } catch (Exception e) {
			if (e.getMessage().equals("余额不足/透支余额超限！"))
            	return -1;//余额不足
        }
        inWallet.increaseFrozenAmount(transitionAmount);
		walletMapper.updateById(outWallet);
		walletMapper.updateById(inWallet);
		return 1;
	}
	
	@Override
	@Transactional
	public int confirmReceipt(int orderId) throws Exception {
		Orders order=ordersMapper.getOrdersById(orderId);
		ordersMapper.receiveOrders(orderId);
		String userIdIn=businessMapper.getBusinessById(order.getBusinessId()).getManager();
		Wallet inWallet=walletMapper.selectById(userIdIn);
		inWallet.unfreeze(new BigDecimal(order.getOrderTotal()));
		walletMapper.updateById(inWallet);
		return 1;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int draw(String userId, String amount){
		String transitionTime=CommonUtil.getCurrentDate();
		Wallet wallet=walletMapper.selectById(userId);
		BigDecimal transitionAmount=new BigDecimal(amount);
		BigDecimal charge=transitionAmount.multiply(new BigDecimal(withdrawalRate));
		Transition transitionDraw = new Transition(transitionTime,transitionAmount,0,userId);
		Transition transitionCharge = new Transition(transitionTime,charge,0,userId);
		transitionMapper.insert(transitionDraw);
		transitionMapper.insert(transitionCharge);
        try {
            wallet.decreaseBalance(charge.add(transitionAmount));
        } catch (Exception e) {
			if (e.getMessage().equals("余额不足/透支余额超限！"))
				return -1;//余额不足
        }
        walletMapper.updateById(wallet);
		return 1;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int recharge(String userId, String amount) throws Exception {
		String transitionTime=CommonUtil.getCurrentDate();
		Wallet wallet=walletMapper.selectById(userId);
		BigDecimal transitionAmount=new BigDecimal(amount);
		Transition transitionRecharge = new Transition(transitionTime,transitionAmount,1,userId);
		transitionMapper.insert(transitionRecharge);
		wallet.increaseBalance(transitionAmount);
		if(isRechargeReward) {
			String[] splitRes=amount.split("[.]");
			int times=Integer.parseInt(splitRes[0])/rechargeThrehold;
			int reward=times*rechargeReward;
			if(reward!=0){
				BigDecimal rewardAmount=new BigDecimal(reward);
				Transition transitionReward = new Transition(transitionTime,rewardAmount,3,userId);
				transitionMapper.insert(transitionReward);
				wallet.increaseBalance(rewardAmount);
			}
		}
		walletMapper.updateById(wallet);
		return 1;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int upgradeVIPWallet(String userId,int VIPmonths,int third_partyPayment){
		Wallet wallet=walletMapper.selectById(userId);
		int ret=0;
		if(third_partyPayment==0) {
			BigDecimal amount=new BigDecimal(VIPmonths).multiply(new BigDecimal(VIPChargeMonthly));
            try {
                wallet.decreaseBalance(amount);
            } catch (Exception e) {
				if (e.getMessage().equals("余额不足/透支余额超限！"))
					return -1;//余额不足
            }
            Transition transition=new Transition(CommonUtil.getCurrentDate(),amount,2,userId,"VIPcharge");
			transitionMapper.insert(transition);
			ret=transition.getTransition_id();
		}
		wallet.openOverdraft();
		User user=userMapper.getVIPInfoById(userId);//开通还是续期
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime expiration;
		if(user.isVIP()) {
			expiration=LocalDateTime.parse(user.getExpirationTime(), dtf);
			expiration=expiration.plusMonths(VIPmonths);
		}
		else {
			String curr=CommonUtil.getCurrentDate();
			LocalDateTime current=LocalDateTime.parse(curr, dtf);
			expiration=current.plusMonths(VIPmonths);
		}
		String exp=expiration.format(dtf);
		userMapper.updateExpirationTimeById(userId,exp,1);
		int temp=walletMapper.updateById(wallet);
		if (ret==0)
			ret=temp;
		return ret;
	}

	@Override
	public List<Transition> listTransitionById(String userId) {
		return transitionMapper.listTransitionById(userId);
	}

}
